package com.ktjy.web.servlet;

import com.alibaba.fastjson.JSON;
import com.ktjy.web.entity.BrandItem;
import com.ktjy.web.entity.Page;
import com.ktjy.web.service.impl.BrandServiceImpl;
import com.ktjy.web.util.R;
import my.framework.anno.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class BrandServlet {
    @RequestMapping("/brand")
    public Object doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String opr = request.getParameter("opr");
        BrandServiceImpl tmp = new BrandServiceImpl();
        R result = null;
        if("page".equals(opr)){
            Page<BrandItem> page=new Page<>();
            String name=request.getParameter("name");
            int pageNo=Integer.parseInt(request.getParameter("pageNo"));
            int pageSize=Integer.parseInt(request.getParameter("pageSize"));

            page.setPageSize(pageSize);
            page.setTotalCount(tmp.count());
            List<BrandItem> list=tmp.page(name,(pageNo-1)*pageSize,pageSize);
            page.setList(list);
            result=R.ok(page);

        }else if("del".equals(opr)){
            int id=Integer.parseInt(request.getParameter("id"));

            int num=tmp.deleteById(id);

            result=R.ok(num);

        }else if("detail".equals(opr)){
            int id=Integer.parseInt(request.getParameter("id"));
            BrandItem data=tmp.selectById(id);

            result=R.ok(data);
        }else if("update".equals(opr)){

            int id=Integer.parseInt(request.getParameter("id"));
            String name=request.getParameter("name");

            System.out.println("ID"+id);
            System.out.println("name"+name);

            BrandItem brandItem=new BrandItem();

            brandItem.setId(id);
            brandItem.setName(name);

            int num =tmp.update(brandItem);

            result=R.ok(num);

        }else if("insert".equals(opr)){

            String name=request.getParameter("name");

            BrandItem brandItem=new BrandItem();

            brandItem.setName(name);

            int num =tmp.insert(brandItem);

            result=R.ok(num);

        }

       return result;
    }
}
